var app = getApp();
var optionsId = ""; //选择后的 规格ID
var specsManage = [];
var optionsMaxCount = 1;
var clicktag = 0;
var WxParse = require("../../../../wxParse/wxParse.js");
let isclick = true;
let siftTop='';
let foshowTop='';

import Dialog from '../../../../dist/dialog/dialog';
Component({
  properties: {
    // 属性值可以在组件使用时指定
    prop_goods_info: {
      type: null, //父组件的商品详情数据
    },
    goodsId: {
      type: Number,
    },
    goodsType: {
      type: String,
    },
    mark: {
      type: String,
    },
    hoet: {
      type: null,
    },
    markId: {
      type: null,
    },
    boxHeight: {
      type: Number,
    },
    xqBoxShow: {
      type: null,
    },
    toker: {
      type: Boolean,
    },
    datop:{
      type:null
    }
  },
  data: {
    reserve_goods: false,//是否为企业预约
    language: "",
    getprice: "",
    // 图片域名
    imgPath: app.globalData.imgPath,
    // 这是tab
    current: 1,
    //设置数据
    goodsInfo: {},
    goods_plugin: {},
    is_o2o: true,
    //o2o商品数量
    o2oCount: 0,
    //企业名字
    o2oName: "",
    //企业电话
    o2oPhone: "",
    o2oLat: "",
    customer_open: true,
    o2oLng: "",
    cartsNum: 0,
    carts: [],
    cartsTotal: 0.0,
    goodsCarts: {},
    popNum: 0,
    popCard: {},
    commentLimit: [], //设置最新5条评论
    //商品详情
    currentTabIndex: "0",
    first_content: "",
    second_content: "",
    third_content: [],
    //标记防止重复加载
    is_first_content: false,
    is_second_content: false,
    is_third_content: false,
    isGoodsLove: false, //是否显示爱心值
    goods_love_cash: 0, //爱心值 现金
    goods_love_deduction: 0, //爱心值抵扣
    goods_love_name: "", //爱心值title,
    specid: "", //规格ID
    popTitle: "",
    popThumb: "",
    popStock: "",
    popPrice: "",
    goodsDescription: "",
    showCart: false,

    btnData: {
      over_top: 500,
      icon_url: `${app.globalData.imgPath}icon-fontclass-zhiding.png`
    },
    //海报显隐
    posterShow: false,
    show1: false,
    posterImg: "",
    timestart: 0,
    timeend: 0,
    isCup: true,
    isGoods: false,
    showDis: true, //控制加入购物车的显示
    store_id: "",
    //活动显示隐藏
    activityShow: false,
    //商城活动
    activityItem: {},
    //商城活动默认第一个
    firstActivityBtn: "",
    //商城活动默认第一个内容
    firstActivityCon: "",
    //商城活动点击开关
    activitySwitch: false,
    openVip: "2",
    salesCount: "", //销量
    minicartStyle: "",
    leftPrice: "",
    OldGoodsNum: "", //保存获取input焦点时的商品数量
    iPnoneBottomBol: false,
    //打开分享弹窗
    showSahre: false,
    // 是否开启好物圈插件
    wechatcircle_open: 0,

    broadcast_data: [], //飘窗订单数据

    //限时购开关
    isBuy: false,
    isTime: false,
    //限时购开始时间
    beginTime: 0,
    //显示购结束时间
    endTime: 0,
    //计算后的倒计时
    countDownObj: {
      day: "00",
      hou: "00",
      min: "00",
      sec: "00",
    },

    /*拓客卡 */
    toker: false,
    customer_development: "",
    effective_time: [],
    effective_day: [],
    many_list: [],
    once_list: [],
    active: 0,

    wx_video_link: 0, //视频号扩展插件
    showVideoLink: false,
    qyPopup: false, //社群营销 二维码弹窗
    article_url: null, // 视频号扩展链接
    limitedTimeCustomName:"限时购", //* 限时购自定义名称
    isMultiSpecs: false, //多规格商品是否显示会员价
    specsVIPPrc: null, //规格商品会员价
    noneArr:[],
    operating_state:1,
    horizon_goods:false,
  }, // 私有数据，可用于模板渲染

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      isclick = true;
      this.getiPnoneBottom();
      let language = wx.getStorageSync("langIndex");
      this.setData({ language: language.en });
      this.getGoodsPage(this.data.prop_goods_info);
      // this.getCommentData();
    },
    moved() {
    },
    detached() {
    },
    ready() {
      // this.footSet();
      let lang = wx.getStorageSync("yz_basic_info").lang.goods;
      let price_text = lang.price ? lang.price : "现价";
      let market_price_text = lang.market_price ? lang.market_price : "原价";
      let that = this;

      that.setData({
        getprice: price_text,
        getMarketPrice: market_price_text
      });
      this.createSelectorQuery()
        .select(".sift")
        .boundingClientRect(function (rect) {
	        if(rect){
		        that.setData({
			        pjtop: rect.top - 80,
		        });
          }
        })
        .exec();
      this.createSelectorQuery()
        .select(".foShowBox")
        .boundingClientRect(function (rect) {
          if(rect){
	          that.setData({
		          xqtop: rect.top - 100,
	          });
          }
        })
        .exec();
    },
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {}, // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {},

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {
      this.getCart();
    },
    hide() {},
    resize() {},
  },
  methods: {
    gotohuiyuan() {
      if (this.data.selfbuy_discount && this.data.selfbuy_discount.link_to_level_page && this.data.selfbuy_discount.link_to_level_page.show == 1) {
        wx.navigateTo({
          url: "/packageB/member/MemberGradeList/MemberGradeList",
        });
      }
    },
    openShare() {
      this.setData({
        showSahre: true,
      });
    },
    closeSharePop() {
      this.setData({
        showSahre: false,
      });
    },
    shareGoods() {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.wechatcircle_products.api.import.import");
      let data = {
        product_list: [
          {
            item_code: that.data.goodsInfo.id,
            title: that.data.goodsInfo.title,
            desc: that.data.goodsInfo.title,
            category_list: ["商品"],
            image_list: that.data.goodsInfo.thumb_url,
            src_wxapp_path: "packageA/detail_v2/detail_v2?id=" + that.data.goodsInfo.id,
            sku_list: [
              {
                sku_id: that.data.goodsInfo.id,
                price: that.data.goodsInfo.price,
                original_price: that.data.goodsInfo.market_price,
                status: 1,
              },
            ],
          },
        ],
      };

      if (isclick) {
        isclick = false;
        app._postNetWork({
          url: urlStr,
          data: data,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              setTimeout(function () {
                isclick = true;
              }, 1000);
              if (wx.openBusinessView) {
                wx.openBusinessView({
                  businessType: "friendGoodsRecommend",
                  extraData: {
                    product: {
                      item_code: that.data.goodsInfo.id,
                      title: that.data.goodsInfo.title,
                      image_list: that.data.goodsInfo.thumb_url,
                    },
                  },
                  success: function (res) {
                    console.log("success", res);
                    that.setData({
                      showSahre: false,
                    });
                  },
                  fail: function (res) {
                    console.log("fail", res);
                    that.setData({
                      showSahre: false,
                    });
                  },
                });
              } else {
                wx.showToast({
                  title: "微信7.0.3及以上版本支持 请先更新微信版本",
                  icon: "none",
                  duration: 1500,
                });
              }
            } else {
              wx.showToast({
                title: res.msg,
                icon: "none",
                duration: 1500,
              });
            }
          },
          fail: function (res) {
            setTimeout(function () {
              isclick = true;
            }, 1000);
            console.log(res);
          },
        });
      }
    },
    getiPnoneBottom() {
      let that = this;
      try {
        var value = wx.getStorageSync("iPhoneBottom");
        if (value) {
          that.setData({
            iPnoneBottomBol: true,
          });
          // Do something with return value
        }
      } catch (e) {
        // Do something when catch error
      }
    },
    callPhone() {
      wx.makePhoneCall({
        phoneNumber: this.data.service_mobile,
      });
    },
    closePop() {
      this.setData({
        show1: false,
      });
    },
    showPop() {
      if (this.data.customer_open) {
        this.setData({
          show1: true,
        });
      }
    },
    clearCart(e) {
      let {key} = e.currentTarget.dataset;
      if(this.data.cartsNum == 0) return app.tips('购物车已清空')
      var that = this;
      var destroyCarts = [];
      this.data.carts.forEach((item) => {
        if(key == 'fail'){
          if(item.is_failure == 1){
            destroyCarts.push(item.id);
          }
        }else{
          destroyCarts.push(item.id);
        }
      });
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.destroy");
      urlStr += "&store_id=" + this.data.store_id;
      urlStr += "&ids=" + destroyCarts;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.getCart();
            that.setData({
              showCart: false,
              popNum: 0,
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    gotoMemberGradeList(e) {
      let o = e.currentTarget.dataset.o;
      if (o == "1") {
        wx.navigateTo({
          url: "/packageB/member/MemberGradeList/MemberGradeList",
        });
      }
    },
    streetClose() {
      this.setData({
        streetShow: false,
      });
    },
    goKb() {
      console.log("打开全部口碑");
      this.setData({
        streetShow: true,
      });
      this.getCommentData();
    },
    closeCs() {
      this.setData({
        showCs: false,
      });
    },
    showCan() {
      console.log("开启参数弹窗");
      this.setData({
        showCs: true,
        is_second_content: true,
        second_content: this.data.goodsInfo.has_many_params,
      });
      this.getCommentData();
    },
    toLink(e) {
      let item = e.currentTarget.dataset.item;
      if (item.min_link) {
        wx.navigateTo({
          url: item.min_link
        });
      }
    },
    onShowLabel() {
      this.setData({
        showLabel: true
      });
    },
    closeLabel() {
      this.setData({
        showLabel: false,
      });
    },
    getTap(e) {
      console.log(e.currentTarget.id);
      let pid = e.currentTarget.id;
      this.setData({
        current: pid,
        getTapNoObsever:true
      });
      if (pid == 1) {
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300,
          success:(res)=>{
            setTimeout(() => {
              this.setData({
                getTapNoObsever:false
              });
            }, 300);
          }
        });
      } else if (pid == 2) {
        wx.pageScrollTo({
          scrollTop: this.data.pjtop + 50,
          duration: 300,
          success:(res)=>{
            setTimeout(() => {
              this.setData({
                getTapNoObsever:false
              });
            }, 300);
          }
        });
      } else if (pid == 3) {
        this.setData({
          xqBoxShow: true,
        });
        wx.pageScrollTo({
          scrollTop: this.data.xqtop +100,
          duration: 300,
          success:(res)=>{
            setTimeout(() => {
              this.setData({
                getTapNoObsever:false
              });
            }, 300);
          }
        });
      }
    },
    //获取时间-限时购
    _timeCompare(begin) {
      let beginTime = new Date(parseInt(begin) * 1000);
      let now = new Date();
      if (now >= beginTime) {
        this.setData({
          isTime: true,
        });
        //开启倒计时
        this._countDown();
      } else {
        this.setData({
          isTime: false,
          isBegTime: true,
          begTimeStr: begin * 1000,
        });
        //开启距离开始倒计时
        this.beginDown();
      }
    },
    //倒计时
    _countDown: function () {
      let newTime = new Date().getTime();
      let endTime = this.data.endTime;
      let obj = null;
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt((time % (60 * 60 * 24)) / 3600);
        let min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60);
        let sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60);
        obj = {
          day: this._timeFormat(day),
          hou: this._timeFormat(hou),
          min: this._timeFormat(min),
          sec: this._timeFormat(sec),
        };
      } else {
        //活动已结束，全部设置为'00'
        obj = {
          day: "00",
          hou: "00",
          min: "00",
          sec: "00",
        };
      }
      this.setData({
        countDownObj: obj,
      });
      if (endTime - newTime < 0) {
        this.setData({
          countDownObj: {
            day: "00",
            hou: "00",
            min: "00",
            sec: "00",
          },
        });
      } else {
        setTimeout(this._countDown.bind(this), 1000);
      }
    },
    //倒计时
    beginDown: function () {
      let newTime = new Date().getTime();
      let endTime = this.data.begTimeStr;
      let obj = null;
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt((time % (60 * 60 * 24)) / 3600);
        let min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60);
        let sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60);
        obj = {
          day: this._timeFormat(day),
          hou: this._timeFormat(hou),
          min: this._timeFormat(min),
          sec: this._timeFormat(sec),
        };
      } else {
        //活动已结束，全部设置为'00'
        this.setData({
          isTime: true,
          isBegTime: false,
        });
        obj = {
          day: "00",
          hou: "00",
          min: "00",
          sec: "00",
        };
      }
      this.setData({
        beginDownObj: obj,
      });
      if (endTime - newTime < 0) {
        this.setData({
          isTime: true,
          isBegTime: false,
        });
        this.setData({
          beginDownObj: {
            day: "00",
            hou: "00",
            min: "00",
            sec: "00",
          },
        });
      } else {
        setTimeout(this.beginDown.bind(this), 1000);
      }
    },
    //小于10的格式化函数
    _timeFormat(param) {
      //小于10的格式化函数
      return param < 10 ? "0" + param : param;
    },
    getCart() {
      var that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.index");
      urlStr += "&store_id=" + this.data.goodsInfo.store_goods.store_id;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              carts: res.data
            });

            that.data.cartsNum = 0;
            that.data.cartsTotal = 0;
            let cartsNum = 0,
              cartsTotal = 0;
            let arrObj = {};
            that.data.carts.forEach((item, index) => {
              arrObj[item.goods_id] = item;
              if (item.goods_id === that.data.goodsInfo.id && item.option_id === optionsId) {
                that.setData({
                  popNum: item.total,
                  popCard: item
                });
              }
              cartsNum += item.total;
              if(item.is_failure == 0){
                cartsTotal += (item.total * item.goods.price);
              }
            });
            that.setData({
              goodsCarts: arrObj,
              cartsNum,
              cartsTotal: parseFloat(cartsTotal).toFixed(2),
              goodsCartsTotal: that.calculateTotal(that.data.carts)
            });

            //计算当前商品数量
            let good = that.data.carts.find((item) => item.goods_id == that.data.goodsId);
            if (good == undefined) {
              that.setData({
                o2oCount: 0,
              });
            }
            that.data.carts.forEach((item) => {
              if (item.goods_id == that.data.goodsId) {
                that.setData({
                  o2oCount: item.total,
                });
              }
              if (item.goods_id === that.data.goodsInfo.id && item.option_id === optionsId) {
                that.setData({
                  popNum: item.total,
                  popCard: item,
                });
              }
            });
            that.getminicartStyle();
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //不同规格的同一商品求和
    calculateTotal(arr) {
      let newArr = []; // 保存求和后的购物车数量列表
      let temp = {};
      let newArr2 = {};
      for (let i in arr) {
        let key = arr[i].goods_id;
        if (temp[key]) {
          temp[key].total = temp[key].total + arr[i].total; //id相同则把数量相加
        } else {
          temp[key] = {};
          temp[key].goods_id = arr[i].goods_id;
          temp[key].total = arr[i].total;
        }
      }
      for (let k in temp) {
        newArr.push(temp[k]);
      }
      newArr.forEach((item) => {
        newArr2[item.goods_id] = item;
      });
      return newArr2;
    },
    //tab 点击
    handleClick(event) {
      let idx = event.detail.index;
      if (this.data.currentTabIndex == idx) {
        return;
      } else {
        this.setData({
          currentTabIndex: idx,
        });
      }
      this.setDataByTabIndex();
    },
    //设置选择后的数据
    setDataByTabIndex() {
      if (this.data.currentTabIndex == "0" && !this.data.is_first_content) {
        this.setData({
          is_first_content: true,
          first_content: this.data.goodsInfo.content,
        });
        let article = this.data.first_content;
        /**
         * WxParse.wxParse(bindName , type, data, target,imagePadding)
         * 1.bindName绑定的数据名(必填)
         * 2.type可以为html或者md(必填)
         * 3.data为传入的具体数据(必填)
         * 4.target为Page对象,一般为this(必填)
         * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
         */
        try {
          // if (article.indexOf('span') > -1) {
          // } else
          if (article.indexOf("&#") <= -1) {
            WxParse.wxParse("article", "html", article, this);
          }
        } catch (e) {
          //TODO handle the exception
        }
      } else if (this.data.currentTabIndex == "1" && !this.data.is_second_content) {
        this.setData({
          is_second_content: true,
          second_content: this.data.goodsInfo.has_many_params,
        });
      } else if (this.data.currentTabIndex == "2" && !this.data.is_third_content) {
        this.setData({
          is_third_content: true,
        });
        //获取评论
        this.getCommentData();
      }
    },
    toTokerList(evt) {
      this.setData({ active: evt.detail.index });
    },
    //获取评论数据
    getCommentData() {
      let that = this;
      let urlStr = app.getNetAddresss("goods.comment.get-comment");
      urlStr += "&goods_id=" + this.data.goodsId;
      urlStr += "&page=1";
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              third_content: res.data.data,
            });
          } else {
            that.setData({
              is_third_content: false,
            });
          }
          if (app._isTextEmpty(that.data.third_content)) {
            console.log("空没评论");
            that.setData({
              thirKong: false,
            });
          } else {
            console.log("不空");
            that.setData({
              thirKong: true,
            });
          }
        },
        fail: function (res) {
          that.setData({
            is_third_content: false,
          });
          console.log(res);
        },
      });
    },
    toBuy() {
      let path = "/packageD/buy/myOrder_v2/myOrder_v2?tag=-2&store_id=" + this.data.goodsInfo.store_goods.store_id + "&goodsId=" + this.data.goodsInfo.id + "&optionsId=" + optionsId + "&total=" + 1;
      if(this.data.horizon_goods){
        // 视界企业商品
        path += '&storeType=horizon'
      }
      wx.navigateTo({
        url: path,
      });
    },
    addCart(e) {
      wx.showLoading();
      let item = e.currentTarget.dataset.item;
      let that = this;
      if (item.vip_level_status && item.vip_level_status.status == 1) {
        wx.showToast({
          title: item.vip_level_status.tips,
          icon: "none",
          duration: 2000,
        });
        return false;
      }
      app._getNetWork({
        showToastIn: false,
        url: app.getNetAddresss("member.member.isValidatePageGoods"),
        success:  (resdata) =>{
          var res = resdata.data;
          
          if (res.result == 1) {
            if (that.data.goodsInfo.has_one_invite_page && that.data.goodsInfo.has_one_invite_page.status === 1 && res.data.is_invite === 0) {
              wx.navigateTo({
                url: "/packageC/member/visit/Inviter/Inviter?fromGood=" + 1,
              });
              return;
            } else {
              let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.store");
              urlStr += "&goods_id=" + item.id;
              urlStr += "&total=1";
              urlStr += "&store_id=" + that.data.goodsInfo.store_goods.store_id;
              app._getNetWork({
                url: urlStr,
                success: function (resdata) {
                  var res = resdata.data;
                  
                  if (res.result == 1) {
                    that.getCart();
                  } else {
                    Dialog.alert({
                      message: res.msg,
                      context:that
                    }).then(() => {
                      // on close
                    });
                  }
                  wx.hideLoading()
                },
                fail: function (res) {
                  wx.hideLoading()
                  console.log(res);
                },
              });
            }
          } else {
            wx.hideLoading()
            Dialog.alert({
              message: res.msg,
              context:this
            }).then(() => {
              // on close
            });
    
          }
        },
      });
    },
    updateCartRequest(id, num) {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.updateNum");
      urlStr += "&id=" + id;
      urlStr += "&num=" + num;
      urlStr += "&store_id=" + this.data.goodsInfo.store_goods.store_id;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (num < 0) {
              that.setData({
                popNum: that.data.popNum - 1,
              });
            } else {
              that.setData({
                popNum: that.data.popNum + 1,
              });
            }
            that.getCart();
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //添加有规格商品到购物车
    addGood(e) {
      // let good = e.currentTarget.dataset.item;
      //价格权限
      if (this.data.goodsInfo.vip_level_status && this.data.goodsInfo.vip_level_status.status == 1) {
        wx.showToast({
          title: this.data.goodsInfo.vip_level_status.tips,
          icon: "none",
          duration: 2000,
        });
        return false;
      }

      this.setData({
        show2: true,
      });
      this.initPopView1(); //初始化弹窗view
    },
    //初始化弹窗view
    initPopView1() {
      optionsId = "";
      specsManage = [];
      this.setData({
        specid: "",
        popNum: 0,
      });
      if (this.data.goodsInfo.has_option === 1) {
        this.isShowMultiSpecsMemPrice(); //是否需要显示多规格会员价
        //是否有规格
        this.setData({
          popTitle: this.data.goodsInfo.title,
          popThumb: this.data.goodsInfo.thumb,
          popStock: this.data.goodsInfo.stock,
          popCard: {},
        });
        if (!this.data.specid.length) {
          this.setData({
            popPrice: this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price,
          });
        }
        this.setData({
          goodsDescription: "请选择",
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          this.setData({
            goodsDescription: this.data.goodsDescription + " " + this.data.goodsInfo.has_many_specs[i].title,
          });
        }

        if (!this.data.optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
            this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[0], "first", i);
          }
        }
      } else {
        this.setData({
          goodsDescription: "",
        });
        optionsMaxCount = this.data.goodsInfo.stock; //设置最大购买量
      }
    },
    isShowMultiSpecsMemPrice() {
      //判断是否需要显示多规格会员价【#70785】
      //注释代码 this.goodsInfo.is_open_micro && Number(this.goodsInfo.is_open_micro) == 1
      //注释原因：后端解释和价格权限插件冲突了 [#80547]
      let _is_open_micro = 0;
      if (this.data.goods_plugin) _is_open_micro = this.data.goods_plugin?.member_price?.is_open_micro || 0;
      if (Number(_is_open_micro) == 1 && this.data.goodsInfo.has_option == 1) {
        this.setData({
          isMultiSpecs: true
        });
      } else {
        this.setData({
          isMultiSpecs: false
        });
      }
    },
    // 关闭弹窗
    close() {
      this.setData({
        show2: false,
        specid: "",
        popNum: 0,
      });
      //确认后清空数值
      optionsId = "";
      specsManage = [];
    },
    //界面选择规格触发事件
    selectSpecs(e, str, i) {
      let id = 0;
      let index = 0;
      let indexl = 0;
      // let data = {};
      if (str == "first") {
        id = e.id;
        index = 0;
        indexl = i;
        // data = e;
      } else {
        id = e.currentTarget.dataset.itemid;
        index = e.currentTarget.dataset.index;
        indexl = e.currentTarget.dataset.indexl;
        // data = e.currentTarget.dataset.item;
      }

      //处理选择池
      this.manageSpecs(indexl, index);
      //处理规格组合选择状态
      this.setGoodsSpecs(indexl, index);
      //设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo(id);
      //判断当前购买总量与库存的关系
      this.getMaxCount();
      console.log(this.data.specid);
      if (this.data.reserve_goods) {
        // 预约商品选择规格
        let json = this.data.reserveJson;
        let arrjson = [];
        // let checkStatus = false;
        for (let i = 0; i < json.length; i++) {
          if (json[i].option_id == optionsId) {
            arrjson = json[i];
          }
        }
        console.log(arrjson);
        this.setData({
          arrjson:arrjson
        });
      }
    },
    //处理选择池
    manageSpecs(indexl, index) {
      let data = this.data.goodsInfo.has_many_specs[indexl].specitem[index];
      var specsObject = new Object();
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;

      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      //排序
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setGoodsDescription();
    },
    //处理goodsDescription 数据
    setGoodsDescription() {
      var description = "";
      //相等代表全选了 体现语句
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.setData({
          goodsDescription: description,
        });
      } else {
        description = "请选择 ";

        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
              description += this.data.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.setData({
          goodsDescription: description,
        });
      }
    },
    //处理规格组合选择状态 过滤数据
    setGoodsSpecs(indexl, index) {
      let specs = this.data.goodsInfo.has_many_specs[indexl].specitem[index];
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
          this.setGoodsSpecsStatus(i, specs.id);
        }
      }
    },
    //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
    setGoodsSpecsStatus(index, id) {
      let specitem = this.data.goodsInfo.has_many_specs[index].specitem;
      let options = []; //数据池
      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
        for (let j = 0; j < _specs.length; j++) {
          if (_specs[j] == id) {
            options.push(this.data.goodsInfo.has_many_options[i]);
            return;
          }
        }
      }
      for (let m = 0; m < options.length; m++) {
        let _specs = options[m].specs.split("_");
        for (let y = 0; y < _specs.length; y++) {
          if (_specs[y] != id && options[m].stock == 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                this.setData({
                  ["data.goodsInfo.has_many_specs[" + index + "].specitem[" + n + "].c"]: true,
                });
                return;
              }
            }
          } else if (_specs[y] != id && options[m].stock > 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                this.setData({
                  ["data.goodsInfo.has_many_specs[" + index + "].specitem[" + n + "].c"]: false,
                });
                return;
              }
            }
          }
        }
      }
    },
    //设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo(id) {
      //根据ID 排序 specsManage.sort();
      specsManage.sort(function (a, b) {
        return a.id - b.id;
      });
      if (specsManage.length === this.data.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
        this.setData({
          specid: goodsSpecs,
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
          if (goodsSpecs === this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
            this.setData({
              popmPrice: this.data.goodsInfo.has_many_options[i].market_price, //设置价格
              popPrice: this.data.goodsInfo.has_many_options[i].product_price, //设置价格
              popThumb: app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb, //设置图片
              popStock: this.data.goodsInfo.has_many_options[i].stock,
            });
            optionsId = this.data.goodsInfo.has_many_options[i].id; //设置规格ID，用于生成订单
            optionsMaxCount = this.data.goodsInfo.has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
            if (optionsMaxCount > 0) {
              this.setData({
                popNum: 0,
              });
            }
            if (this.data.isMultiSpecs) this.getMemberPrice(optionsId);
            break;
          }
        }
        for (let i = 0; i < this.data.carts.length; i++) {
          if (this.data.carts[i].goods_id === this.data.goodsInfo.id && this.data.carts[i].option_id === optionsId) {
            this.setData({
              popNum: this.data.carts[i].total,
              popCard: this.data.carts[i],
            });
            break;
          }
          this.setData({
            popNum: 0,
            popCard: {},
          });
        }
      } else {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        this.setData({
          specid: goodsSpecs,
        });
      }
    },
    //处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); //先变成数组
      //_specs.sort();//排序
      _specs.sort(function (a, b) {
        return a - b;
      });
      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"

      return goodsSpecs;
    },
    //判断当前购买总量与库存的关系
    getMaxCount() {
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          //库存不足
          this.setData({
            popNum: 0,
          });
        }
        if (this.data.popNum > optionsMaxCount) {
          this.setData({
            popNum: optionsMaxCount,
          });
        }
      }
    },
    //弹窗提交确认
    submitAction() {
      // 判断宠物医院插件是否有绑定手机号码
      // if (app._isTextEmpty(wx.getStorageSync('pet_status'))) {

      // } else {
      //   console.log(wx.getStorageSync('pet_status'))
      //   if (wx.getStorageSync('pet_status') == 1) {
      //     wx.navigateTo({
      //       // url: '/packageA/member/editmobile/editmobile',
      //       url: '/packageC/hospital/bindMobile/bindMobile',
      //       success: function (res) {
      //         wx.showToast({
      //           title: '购买前请绑定手机号',
      //           icon: 'none'
      //         })
      //       }
      //     })
      //     return
      //   }
      // }
      if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
        //请选择规格
        this.setData({
          show2: false,
        });
        wx.showToast({
          title: this.data.goodsDescription,
          icon: "none",
          duration: 1500,
        });
        return;
      }
      //处理参数
      this.addCartRequest(this.data.goodsInfo.id, optionsId);
    },
    //加入购物车网络操作
    addCartRequest(_goodsId, _optionsId) {
      if (optionsMaxCount === 0) {
        //库存不足
        wx.showToast({
          title: "商品库存不足",
          icon: "none",
          duration: 1500,
        });
        return;
      }
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.store");
      urlStr += "&goods_id=" + _goodsId;
      urlStr += "&total=1";
      urlStr += "&option_id=" + _optionsId;
      urlStr += "&store_id=" + this.data.goodsInfo.store_goods.store_id;
      app._getNetWork({
        url: urlStr,
        success:  (resdata) =>{
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              popNum: that.data.popNum + 1,
            });
            that.getCart();
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 1500,
            });
          } else {
            Dialog.alert({
              message: res.msg,
              context:this
            }).then(() => {
              // on close
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    gotoList() {
      let _url = "/packageC/o2o/o2oStore/o2oStore?store_id=" + this.data.goodsInfo.store_goods.store_id;
      if(this.data.prop_goods_info?.specify_show?.url) _url = this.data.prop_goods_info?.specify_show?.url;
      wx.navigateTo({
        url: _url
      });
    },
    gophone(e) {
      let mobile = e.currentTarget.dataset.mobile;
      wx.makePhoneCall({
        phoneNumber: mobile,
      });
    },
    goToAdress() {
      let latitude = this.data.o2oLat;
      let longitude = this.data.o2oLng;
      let store_name = this.data.o2oName;
      let point = app.BMapTransqqMap(parseFloat(longitude), parseFloat(latitude));
      wx.openLocation({
        latitude: point.lat,
        longitude: point.lng,
        scale: 18,
        name: store_name,
      });
    },
    goShowCart() {
      if (!this.data.showCart && this.data.cartsNum > 0) {
        this.setData({
          showCart: true,
        });
      } else {
        this.setData({
          showCart: false,
        });
      }
      this.getminicartStyle();
    },
    goodsOrder(e) {
      if(this.data.operating_state == 1) {
        app.tips("企业休息中")
        return
      };
      let that = this;
      app._getNetWork({
        showToastIn: false,
        url: app.getNetAddresss("member.member.isValidatePageGoods"),
        success: async (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.data.goodsInfo.has_one_invite_page && that.data.goodsInfo.has_one_invite_page.status === 1 && res.data.is_invite === 0) {
              wx.navigateTo({
                url: "/packageC/member/visit/Inviter/Inviter?fromGood=" + 1,
              });
              return;
            } else {
              //判断是否上面安装的商品
              let confirmFlag = await this.isHasDifferType(that.data.goodsCarts);
              if (!confirmFlag) {
                return;
              }
              let sum = 0;
              that.data.carts.forEach((val) => {
                sum += val.total;
              });
              if (sum == 0) {
                return;
              }
              if (Object.keys(that.data.goodsCarts).length == 0) {
                return;
              } else {
                wx.navigateTo({
                  url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=store&store_id=" + that.data.goodsInfo.store_goods.store_id,
                });
              }
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
      });
    },
    async isHasDifferType(data) {
      //企业购物车提交结算的时候，要判断当前购物车中是否同时存在普通商品和安装服务商品，如果同时存在，要弹框提示
      // 商品不是安装服务商品，直接没有live_install这个字段
      let open_state = 0; //有安装服务的商品
      let clone_state = 0; //没安装服务的商品
      let plugin_name = "";
      for (let item in data) {
        if (item.live_install && item.live_install.open_state == 1) {
          open_state += 1;
          plugin_name = item.live_install.plugin_name;
        } else {
          clone_state += 1;
        }
      }
      if (open_state != 0 && clone_state != 0) {
        let confirm = await app.confirm(`普通商品与${plugin_name}商品一同下单将无法享受${plugin_name}，是否继续下单？`);
        return confirm;
        //都有值说明存在 两种 不同商品类型，提示框显示
        // wx.showModal({
        //   title: '提示',
        //   content: `普通商品与${plugin_name}商品一同下单将无法享受${plugin_name}，是否继续下单？`,
        //   success:(res)=> {
        //     if (res.confirm) {
        //       this._goodsOrder(data, true);
        //     } else if (res.cancel) {

        //     }
        //   }
        // });
      }
      return true;
    },
    //跳转企业商品的详情
    goToGoodsO2O(e) {
      let goods = e.currentTarget.dataset.item;
      if (this.data.store.operating_state !== 1) {
        wx.redirectTo({
          url: "/packageA/detail_v2/detail_v2?id=" + goods.goods_id + "&tag=o2o" + "&store_id=" + this.data.goodsInfo.store_goods.store_id,
        });
      }
    },
    //海报生成
    postShow() {
      this.setData({
        posterShow: true,
        showSahre: false,
      });
      return;
      // let that = this;
      // if (that.data.posterImg) {
      //   this.setData({
      //     posterShow: true
      //   });
      // } else {
      //   wx.showLoading({
      //     title: '海报生成中',
      //   });
      //   let urlStr = app.getNetAddresss("goods.goods-poster.generate-goods-poster");
      //   urlStr += "&id=" + this.data.goodsId;
      //   app._getNetWork({
      //     showToastIn: false,
      //     url: urlStr,
      //     success: function (resdata) {
      //       var res = resdata.data;
      //       if (res.result == 1) {
      //         that.setData({
      //           posterImg: res.data,
      //           posterShow: true
      //         });
      //       } else {
      //         that.setData({
      //           posterShow: false
      //         });
      //         wx.showToast({
      //           icon: 'none',
      //           title: res.msg,
      //           duration: 1500
      //         });
      //       }
      //       wx.hideLoading();
      //     },
      //     fail: function (res) {
      //       wx.hideLoading();
      //       console.log(res);
      //     }
      //   });
      //   setTimeout(function () {
      //     wx.hideLoading();
      //   }, 5000);
      // }
    },
    posterClose() {
      this.setData({
        posterShow: false,
      });
    },
    //点击开始时的时间
    timestart: function (e) {
      var _this = this;
      _this.setData({
        timestart: e.timeStamp,
      });
    },

    //点击结束的时间
    timeend: function (e) {
      var _this = this;
      _this.setData({
        timeend: e.timeStamp,
      });
    },
    saveImg() {
      // var times = _this.data.timeend - _this.data.timestart;
      wx.getSetting({
        success(res) {
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            wx.authorize({
              scope: "scope.writePhotosAlbum",
              success() {
                console.log("授权成功");
              },
            });
          }
        },
      });
      var imgSrc = this.data.posterImg.image_url;
      wx.downloadFile({
        url: imgSrc,
        success: function (res) {
          console.log(res);
          //图片保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              wx.showToast({
                title: "保存成功",
                icon: "none",
                duration: 2000,
              });
            },
            fail: function (err) {
              console.log(err);
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                console.log("当初用户拒绝，再次发起授权");
                wx.openSetting({
                  success(settingdata) {
                    if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                      wx.showToast({
                        icon: "none",
                        title: "获取权限成功,再次长按保存图片",
                        duration: 1500,
                      });
                    } else {
                      wx.showToast({
                        icon: "none",
                        title: "获取权限失败,保存图片需要用户授权",
                        duration: 1500,
                      });
                    }
                  },
                });
              }
            },
            complete(res) {
              console.log(res);
            },
          });
        },
      });
    },
    gotoMember() {
      wx.reLaunch({
        url: "/packageG/member_v2/member_v2",
      });
    },
    gotoindex() {
      wx.reLaunch({
        url: this.data.prop_goods_info?.store_head_link||"/packageG/index/index"
      });
    },
    //推广商品跳转
    pushGoodGoto(e) {
      let itemdata = e.currentTarget.dataset.itemdata;
      wx.navigateTo({
        url: "/packageA/detail_v2/detail_v2?id=" + itemdata.id,
      });
    },
    gotoChat(evt){
      let url = evt.currentTarget.dataset.cservice+"&goods_id="+this.data.goodsId;
      wx.navigateTo({
        url: url,
        fail:(err)=>{
          app.tips("客服路由出错");
        }
      });
    },
    // 视界企业商品立即购买
    tapHorizonBuy(){
      // this.goodsOrder();
      if(this.data.goodsInfo.has_option == 1 && this.data.o2oCount <= 0){
        app.tips('请选择规格')
        this.addGood()
        return
      }
      this.toBuy()
    },
    getGoodsPage(data) {
      // data全部数据
      let that = this;
      if(data.plugin && data.plugin.horizon && data.plugin.horizon.is_store_count == 1){
        // 视界购买设备次数商品
        this.setData({
          horizon_goods: true
        })
      }
      if(data.reserve_goods){
        //是否是预约商品
        this.setData({
          reserve_goods:data.reserve_goods
        });
      }
      if (data && data.get_goods) {

        that.init(data.get_store_info);
        if(data.member_cart){
          that.getFirstCart(data.member_cart);
        }
        that.setData({
          service_QRcode: data.customer_service.service_QRcode,
          service_mobile: data.customer_service.service_mobile,
          cservice: data.customer_service.cservice,
          showMember: data.display_page == "1" ? true : false,
        });
    
        if(data.is_favorite){
          this.setData({
            favorite : (data.is_favorite.status == 1 ? true : false)
          });
        }
        that.getData(data.get_goods);
        // console.log(that.data.service_mobile,that.data.service_QRcode);

        if(this.data.customer_development) {
          setTimeout(()=>{
            this.setData({
              toker: true,
            });
            // tab的下划线问题
          },500);
        }
        
        if(data.plugin){
          that.setData({
            broadcast_data: data.plugin.broadcast_data,
            goods_plugin: data.plugin || {},
            customer_development: data.plugin.customer_development,
          })
          // 自购省
          if (data.plugin.selfbuy_discount) {
            that.setData({
              selfbuy_discount: data.plugin.selfbuy_discount,
            });
          }
          // 租赁商品
          if (!app._isTextEmpty(data.plugin.lease_toy)) {
            this.setData({
              isRent: data.plugin.lease_toy.is_lease == 1 ? true : false,
              isRentBuyShow: data.plugin.lease_toy.immed_goods_id == 0 ? false : true,
            });
            if (!app._isTextEmpty(data.plugin.lease_toy.is_rights)) {
              this.setData({
                isRight: data.plugin.lease_toy.is_rights == 1 ? true : false,
              });
            }
          }

          // 是否开启好物圈插件
          if (data.plugin.wechatcircle_open && data.plugin.wechatcircle_open == 1) {
            that.setData({
              wechatcircle_open: 1,
            });
          }

          // 视频号链接
          if (data.plugin && data.plugin.wx_video_link) {
            that.setData({
              wx_video_link: data.plugin.wx_video_link,
            });
          }
        }

        
      } else {
        that.setData({
          showDis: false,
          show8: true,
        });
      }
    },
    //收藏操作
    onFavorite(e) {
      let favorite = e.currentTarget.dataset.favorite;
      console.log(favorite);
      favorite ? this.removeFavorite() : this.addFavorite();
    },
    closeCalendar(){
      this.setData({
        showCalendar:false
      });
    },
    formatDate(date) {
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    },
    onConfirmCalendar(date) {
      this.setData({
        calendar_data:this.formatDate(date.detail)
      });
      let selectTime = Date.parse(this.data.calendar_data) / 1000;
      let timeArr = this.data.reserveDayArr;
      let selectStatus = false;
      let obj = [];
      for (let i = 0; i < timeArr.length; i++) {
        if (selectTime == timeArr[i].time) {
          obj.push(timeArr[i]);
          selectStatus = true;
        }
      }
      // 可以选的时间
      if (selectStatus) {
        this.setData({
          showCalendar:false,
          reserveJson:obj,
          show2:true
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[0], "first", i);
        }
      } else {
        // 不可以预约的时间
        this.calendar_data = "";
        wx.showToast({
          title: '所选日期不可预约',
          icon:'none'
        });
      }
    },
    confirmTap(){
      let that = this;
      let json = this.data.reserveJson;
      this.data.arrjson = [];
      for (let i = 0; i < json.length; i++) {
        if (json[i].option_id == optionsId) {
          // this.data.arrjson = json[i];
          this.setData({
            arrjson:json[i]
          });
        }
      }

      if (!this.data.arrjson.id) {
        Toast("请选择日期");
        return;
      }
      if (!optionsId) {
        Toast("请选择规格");
        return;
      }
      console.log(json);
      let urlStr = app.getNetAddresss("plugin.store-reserve.frontend.goods.verify");
      app._getNetWork({
        url: urlStr,
        data:{
          option_id:optionsId,
          goods_id:that.data.goodsInfo.id
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.navigateTo({
              url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=reserve&store_id=" + that.data.goodsInfo.store_goods.store_id + "&goodsId=" + that.data.goodsInfo.id + "&optionsId=" + optionsId + "&total=" + 1+"&date_id="+that.data.arrjson.id,
            });
          }else{
            wx.showModal({
              icon: "none",
              showCancel:false,
              content: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    tapReserve(){
      let urlStr = app.getNetAddresss("plugin.store-reserve.frontend.date.getOptionDate");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success:(resdata)=>{
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res);
            this.setData({
              showCalendar:true, // 预约日历显示
              reserveDayArr:res.data,
            });
            let arr = [];
            let strArr = [];
            let no = 0;
            if (this.data.reserveDayArr.length > 0) {
              this.data.reserveDayArr.forEach((element, ind, arrs) => {
                if (arr.length == 0) {
                  arr.push(element);
                } else {
                  // arr数组有存在time一样的对象时，比较一下is_reserve看他是不是false
                  if (arr[no].time == element.time) {
                    if (arr[no].is_reserve) {
                      // 如果原来存在数组is_reserve为true的话，这个天数默认为true
                      arr[no] = element;
                      arr[no].is_reserve = true;
                    } else {
                      //如果原来的数组is_reserve为false的话还有机会
                      if (element.is_reserve == false) {
                        // 传进来的数组为false保持为false
                        arr[no] = element;
                      } else {
                        // 传进来的数组为true的话没有机会了
                        arr[no] = element;
                        arr[no].is_reserve = true;
                      }
                    }
                  } else {
                    no = no + 1;
                    arr.push(element);
                  }
                }
              });
            }
            for (let k = 0; k < arr.length; k++) {
              if (arr[k].is_reserve) {
                strArr.push(String(arr[k].date));
              }
            }
            let that = this;
            this.setData({
              noneArr:strArr,
              show2:false,
              formatter(day){
                return that.formatters(day);
              }
            });
          }else{
            if(res.msg == '没有规格id'){
              wx.showToast({
                title: '请选择规格',
                icon:'none'
              });
            }else{
              wx.showToast({
                title: res.msg,
                icon:'none'
              });
            }
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    formatters(day) {
      let month = day.date.getMonth() + 1;
      let date = day.date.getDate();
      if (month < 10) {
        month = `0${month}`;
      }
      if (date < 10) {
        date = `0${date}`;
      }
      if (!day.type) {
        // 默认日期
        day.bottomInfo = "不可预约";
        day.className = "calendar_data";
      }
      if (this.data.noneArr) {
        for (let k = 0; k < this.data.noneArr.length; k++) {
          if (`${month}-${date}` == this.data.noneArr[k]) {
            day.bottomInfo  = "可预约";
            day.className = "calendar_data";
          }
        }
      }
      if (day.bottomInfo != "可预约") {
        day.bottomInfo  = "不可预约";
        day.type = "disabled";
      }
      return day;
    },
    //移除收藏
    removeFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.destroy");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: false,
            });
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          } // else {

          //}
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //添加收藏
    addFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.store");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: true,
            });
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //获取数据
    getData(data) {
      // get_goods数据
      try {
        if (Number(data.market_price) == 0) {
          data.notMarket_price = 0;
        } else {
          data.notMarket_price = 1;
        }
      } catch (err) {
        console.log(err);
      }
      this.setData({
        goodsInfo: data,
        xqBoxShow:data.detail_show?true:false,
        commentLimit: data.get_comment.data ? data.get_comment.data.slice(0, 5) : [],
      });
      // 分享的自定义图片
      wx.setStorageSync("GoddsShareImg", data.thumb);
      //* 限时购自定义名称
      if(data.buy_limit&&data.buy_limit.status&&data.buy_limit.display_name){
        this.setData({
          limitedTimeCustomName:data.buy_limit.display_name
        });
      }
      this.setData({
        salesCount: this.data.goodsInfo.show_sales + this.data.goodsInfo.virtual_sales,
      });
      if (this.data.goodsInfo.member_discount) {
        if (app._isTextEmpty(this.data.goodsInfo.member_discount.discount)) {
          this.setData({
            openVip: 1,
          });
        } else {
          this.setData({
            openVip: this.data.goodsInfo.member_discount.discount,
          });
        }
      }
      this.initPopView(); //初始化弹窗view
      this.initPopView2(); //初始化弹窗view2 无规格
      this.setDataByTabIndex(); //设置商品详情
      this.setIsAddCart(); //判断是否能加入购物车
      this.setIsLove(); //判断是否有爱心值
      this.setData({
        isGoods: true,
      });

      this.setData({
        store_id: this.data.goodsInfo.store_goods.store_id,
        isMarginBottom: app._isTextEmpty(data.show_push) ? false : true,
      });

      //限时购
      if (!app._isTextEmpty(data.buy_limit)) {
        this.setData({
          isBuy: data.buy_limit.status == 1 ? true : false,
        });
        this.data.beginTime = data.buy_limit.start_time;
        this.data.endTime = data.buy_limit.end_time * 1000;
        //判断倒计时模块是否开启
        this._timeCompare(this.data.beginTime);
      }
      if (data.goods_sale && data.goods_sale.sale_count != 0) {
        this.setData({
          firstActivityBtn: data.goods_sale.first_strip_key.name,
        });
        if (data.goods_sale.first_strip_key.type == "array") {
          data.goods_sale.first_strip_key.value.forEach((item, index) => {
            if (index == 0) {
              this.setData({
                firstActivityCon: item,
              });
            } else {
              this.setData({
                firstActivityCon: this.data.firstActivityCon + "," + item,
              });
            }
          });
        } else {
          this.setData({
            firstActivityCon: data.goods_sale.first_strip_key.value,
          });
        }
        this.setData({
          activitySwitch: true,
          activityItem: data.goods_sale,
        });
        this.showDefaultActivity(data.goods_sale);
      } else {
        this.setData({
          activitySwitch: false,
        });
      }
    },
    //初始化弹窗view
    initPopView() {
      this.setData({
        popThumb: this.data.goodsInfo.thumb, //设置默认图片
        popStock: this.data.goodsInfo.stock, //设置默认库存
      });
      if (this.data.goodsInfo.has_option == 1) {
        this.setData({
          popPrice: this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price, //设置默认价格
        });
      } else {
        this.setData({
          popPrice: this.data.goodsInfo.price,
        });
      }
      this.setData({
        goodsDescription: "选择",
      });
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        this.setData({
          goodsDescription: this.data.goodsDescription + " " + this.data.goodsInfo.has_many_specs[i].title,
        });
      }
    },
    initPopView2() {
      if (this.data.goodsInfo.has_option != 1) {
        this.setData({
          popThumb: this.data.goodsInfo.thumb, //设置默认图片
          popStock: this.data.goodsInfo.stock, //设置默认库存
          popPrice: this.data.goodsInfo.price, //设置默认价格
          goodsDescription: "",
        });
        optionsMaxCount = this.data.goodsInfo.stock; //设置最大购买量
      }
    },
    //判断是否能加入购物车
    setIsAddCart() {
      //为空是老数据默认值问题
      if (app._isTextEmpty(this.data.goodsInfo.buy_way) || this.data.goodsInfo.buy_way == "0") {
        this.setData({
          isAddCart: true,
        });
      }
      //不能加入 金币产品
      if (this.data.goodsInfo.buy_way == 1) {
        this.setData({
          isAddCart: false,
        });
      }
    },

    //跳转评论详情
    toContentInfo(e) {
      let jsondata = e.currentTarget.dataset.jsondata;
      wx.navigateTo({
        url: "/packageD/member/CommentDetails/CommentDetails?order_id=" + jsondata.order_id + "&goods_id=" + jsondata.goods_id + "&uid=" + jsondata.uid + "&comment_id=" + jsondata.id,
      });
    },
    //是否有爱心值
    setIsLove() {
      if (this.data.goods_plugin.goods_love) {
        this.setData({
          isGoodsLove: true,
        });
        let love_cash = this.data.goodsInfo.price - this.data.goods_plugin.goods_love.amountOfMoney;
        this.setData({
          goods_love_cash: Number(love_cash.toString().match(/^\d+(?:\.\d{0,2})?/)),
        });
        this.setData({
          goods_love_deduction: this.data.goods_plugin.goods_love.amountOfCoin,
          goods_love_name: this.data.goods_plugin.goods_love.name,
        });
      } else {
        this.setData({
          isGoodsLove: false,
        });
      }
    },
    //跳转优惠券领取
    gotoCoupon() {
      wx.navigateTo({
        url: "/packageC/o2o/store_coupon/store_coupon?id=" + this.data.goodsInfo.store_goods.store_id,
      });
    },
    activityShowFun() {
      this.setData({
        activityShow: true,
      });
    },
    openSepc() {//判断有规格还是没有规格的商品
      let hasOptions = this.data.prop_goods_info?.get_goods?.has_many_options;
      console.log(hasOptions);
      if(hasOptions.length > 0) {
        this.setData({
          show2:true,
        })
        this.initPopView1(); //初始化弹窗view
      } else {
        wx.navigateTo({
          url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=-2&store_id=" + this.data.goodsInfo.store_goods.store_id + "&goodsId=" + this.data.goodsInfo.id + "&optionsId=" + optionsId + "&total=" + 1,
        });
      }
      
    },
    activityShowBtn() {
      this.setData({
        activityShow: false,
      });
    },
    //显示商城活动默认活动
    showDefaultActivity(val) {
      if (val.first_strip_key == "coupon") {
        this.setData({
          firstActivityBtn: "购买返券",
          firstActivityCon: "商品订单完成返优惠券",
        });
      } else if (val.first_strip_key == "deduction_proportion" || val.first_strip_key == "award_proportion") {
        this.setData({
          firstActivityBtn: val.love_name,
          firstActivityCon: "最高抵扣" + val.love_name + val.deduction_proportion + ",购买赠送" + val.award_proportion + val.love_name,
        });
      } else if (val.first_strip_key == "max_point_deduct" || val.first_strip_key == "point") {
        this.setData({
          firstActivityBtn: val.point_name,
          firstActivityCon: "最高抵扣" + val.point_name + val.max_point_deduct + ",购买赠送" + val.point + val.point_name,
        });
      } else if (val.first_strip_key == "ed_full") {
        this.setData({
          firstActivityBtn: "满减",
          firstActivityCon: "本商品满" + this.data.language["money"] + val.ed_full + "立减" + this.data.language["money"] + val.ed_reduction + "",
        });
      } else if (val.first_strip_key == "ed_money" || val.first_strip_key == "ed_num") {
        this.setData({
          firstActivityBtn: "包邮",
        });
        if (val.first_strip_key == "ed_money" && val.ed_num == 0) {
          this.setData({
            firstActivityCon: "本商品满" + this.data.language["money"] + val.ed_money + this.data.language["元"] + "包邮",
          });
        } else if (val.first_strip_key == "ed_num" && val.ed_money == 0) {
          this.setData({
            firstActivityCon: "本商品满" + val.ed_num + "件包邮",
          });
        } else {
          this.setData({
            firstActivityCon: "本商品满" + this.data.language["money"] + val.ed_money + this.data.language["元"] + "包邮" + ",满" + val.ed_num + "件包邮",
          });
        }
      } else if (val.first_strip_key == "award_balance") {
        this.setData({
          firstActivityBtn: "余额",
          firstActivityCon: "购买赠送余额" + val.award_balance + this.data.language["元"],
        });
      } else {
        return;
      }
    },
    init(data) {
      // get_store_info企业数据
      this.setData({
        operating_state:data.operating_state,
        o2oName: data.store_name,
        o2oPhone: data.store_mobile,
        o2oLat: data.lat,
        o2oLng: data.lng,
      });
    },
    getFirstCart(data) {
      // member_cart数据
      this.setData({
        carts: data,
        goodsCarts: [],
        cartsNum: 0,
        cartsTotal: 0
      });
      let arrObj = {};
      this.data.carts.forEach(item => {
        arrObj[item.goods_id] = item;
        if (
          item.goods_id === this.data.goodsInfo.id &&
          item.option_id === optionsId
        ) {
          this.setData({
            popNum: item.total,
            popCard: item
          });
        }
        this.data.cartsNum = this.data.cartsNum + item.total;
        if(item.is_failure == 0){
          this.data.cartsTotal += (item.total * item.goods.price);
        }
      });
      this.setData({
        goodsCarts: arrObj,
        goodsCartsTotal: this.calculateTotal(this.data.carts),
        cartsTotal: parseFloat(this.data.cartsTotal).toFixed(2),
        cartsNum:this.data.cartsNum
      });
    },
    //足迹记录
    footSet() {
      if (!this.data.isGoods) {
        return;
      }

      let urlStr = app.getNetAddresss("member.member-history.store");
      urlStr += "&goods_id=" + this.properties.goodsId + "&mark=" + this.properties.mark + "&mark_id=" + this.properties.markId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {},
        fail: function (res) {},
      });
    },
    goTOHome() {
      wx.redirectTo({
        url: "/packageC/o2o/o2oHome/o2oHome",
      });
    },
    trggleCart() {
      if (this.data.carts.length === 0 && !this.data.showCart) {
        return;
      }
      this.setData({
        showCart: !this.data.showCart,
      });
      this.getminicartStyle();
    },
    getminicartStyle() {
      if (this.data.showCart) {
        this.setData({
          minicartStyle: "display: none;transform: translateY(-100%)",
          leftPrice: "transform: translateX(-60px);",
        });
      } else {
        this.setData({
          minicartStyle: "display: block;transform: translateY(0)",
          leftPrice: "",
        });
      }
    },
    updateCart1btn(e) {
      let id = e.currentTarget.dataset.id;
      let num = e.currentTarget.dataset.num;
      this.updateCart1(id, num);
    },
    updateCart1(id, num) {
	    // id是购物车id
      if (num < 0) {
        var total = 0;
        this.data.carts.forEach((item) => {
          if (item.id == id) {
            total = item.total;
          }
        });

        if (total + num <= 0) {
          if (clicktag === 0) {
            clicktag = 1;
            this.delItemByCart1(id);
            setTimeout(function () {
              clicktag = 0;
            }, 500);
          }
          return;
        }
        if (clicktag === 0) {
          clicktag = 1;
          this.updateCartRequest(id, num);
          setTimeout(function () {
            clicktag = 0;
          }, 500);
        }
      } else {
        if (specsManage.length == this.data.goodsInfo.has_many_specs.length && this.data.popNum == optionsMaxCount) {
          wx.showToast({
            icon: "none",
            title: "数量超出范围",
            duration: 1500,
          });
          return;
        }
        if (clicktag === 0) {
          clicktag = 1;
          this.updateCartRequest(id, num);
          setTimeout(function () {
            clicktag = 0;
          }, 500);
        }
      }
    },
    delItemByCart1(cart_id) {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.destroy");
      app._getNetWork({
        url: urlStr,
        data: {
          store_id: this.data.store_id,
          ids: cart_id,
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.getCart();
            that.setData({
              popNum: that.data.popNum - 1,
              showCart: false,
              minicartStyle: "display: block;transform: translateY(0)",
              leftPrice: "",
            });
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    updateCartbtn(e) {
      let id = e.currentTarget.dataset.id;
      let num = e.currentTarget.dataset.num;
      this.updateCart(id, num);
    },
    updateCart(id, num) {
	    // id是goods_id
      if (num < 0) {
        var total = 0;
        this.data.carts.forEach((item) => {
          if (item.goods_id == id) {
            total = item.total;
          }
        });
        if (total + num <= 0) {
          this.delItemByCart(id);
          return;
        }
      }
      let that = this;
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.updateNum");
      app._getNetWork({
        url: urlStr,
        data: {
          num: num,
          store_id: this.data.store_id,
          goods_id: id,
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.getCart();
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
            that.getCart();
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    delItemByCart(cart_id) {
      let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.shoppingCart.member-cart.destroy");
      app._getNetWork({
        url: urlStr,
        data: {
          store_id: this.data.store_id,
          goods_id: cart_id,
        },
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            this.getCart();
            this.setData({
              showCart: false
            });
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    clickCount(e) {
      let total = e.currentTarget.dataset.total;
      this.setData({
        OldGoodsNum: total,
      });
    },
    changeCount(e) {
      let data = e.detail.value;
      let id = e.currentTarget.dataset.id;
      if (data < 0) {
        wx.showToast({
	        icon: "none",
          title: "商品数量不能为负数",
          duration: 1500,
        });
	      this.setData({
          o2oCount: this.data.OldGoodsNum,
        });
	      this.getCart();
        return;
      }

	    if (data == this.data.OldGoodsNum) {
		    return;
	    }

      if (data < this.data.OldGoodsNum) {
        let lowerNum = this.data.OldGoodsNum - data;
	      this.updateCart(id, -lowerNum);
      } else if (data > this.data.OldGoodsNum) {
        let addNum = data - this.data.OldGoodsNum;
	      this.updateCart(id, addNum);
      }
    },
    getVideoLink() {
      wx.showLoading({
        title: "正在生成中...",
      });
      // 生成视频号链接
      let that = this;
      let urlStr = app.getNetAddresss("plugin.wx-video-link.frontend.index.index");
      urlStr += "&id=" + this.properties.goodsId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.article_url == "" || res.data.article_url == null || res.data.article_url == undefined) {
              setTimeout(() => {
                that.getVideoLink();
              }, 3000);
            } else {
              that.setData({
                article_url: res.data.article_url,
                showVideoLink: true,
                showSahre: false,
              });
              setTimeout(function () {
                wx.hideLoading();
              }, 800);
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    // 复制链接
    onCopy() {
      this.onClipboardData(this.data.article_url)
      this.setData({
        showVideoLink: false,
        article_url: "",
      });
    },
    getMemberPrice(_optionsId) {
      if (!_optionsId) return;
      let specsVIPPrc = 0;
      this.setData({specsVIPPrc});
      let urlStr = app.getNetAddresss("goods.other-info.option-vpi-price");
      urlStr += "&option_id=" + _optionsId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            specsVIPPrc = res.data.vip_price || null;
          } else {
            specsVIPPrc = null;
          }
          this.setData({specsVIPPrc});
        },
        fail: function (res) {
          specsVIPPrc = null;
          this.setData({specsVIPPrc});
        },
      });

    },
    // ---------------- 引导加群end
    toGroupCode() {
      if(this.data.goods_plugin.group_code.jump_mode === 'home') {
        wx.reLaunch({
          url: '/packageE/groupCode/groupCode',
        });
      }else if(this.data.goods_plugin.group_code.code_mini_url){
        wx.navigateTo({
          url: this.data.goods_plugin.group_code.code_mini_url
        });
      }
    },
    getQYCode(e){
      let status = e.currentTarget.dataset.status;
      this.setData({qyPopup: status})
    },
    getShortLink(){
      app._postNetWork({
        url:app.getNetAddresss("plugin.wechat-short-link.frontend.index.get-url"),
        data:{
          goods_id: this.data.goodsInfo.id,
          applet_url: `packageA/detail_v2/detail_v2?id=${this.data.goodsInfo.id}&tag=o2o&store_id=${this.data.store_id}`
        },
        success:res => {
          console.log(res)
          if(res.data.result == 1){
            this.setData({
              videoLinkText: res.data.data.text,
              showShortLink: true,
              showSahre: false
            });
          }else{
            app.tips(res.data.msg)
          }
        }
      })
    },
    onClipboardData(data){
      wx.setClipboardData({
        data: data,
        success(res) {
          wx.showToast({
            icon: 'none',
            title: '复制成功',
            duration: 1000
          });
        },fail(err){
          console.log(err);
        }
      });
    },
    onCopyShortLink(){
      this.onClipboardData(this.data.videoLinkText);
    },
    clonePop(e){
      let { tag, status } = e.target.dataset;
      this.setData({
        [tag]: status
      })
    }
  },
  observers:{
    'datop':function(obs){
      let that = this;
      if(that.data.getTapNoObsever){
        return;
      }
      this.createSelectorQuery()
        .select(".sift")
        .boundingClientRect(function (rect) {
	        if(rect) {
		        siftTop = rect.top -50;
	        }
        })
        .exec();
      this.createSelectorQuery()
        .select(".foShowBox")
        .boundingClientRect(function (rect) {
          if(rect) {
	          foshowTop = rect.top - 150;
          }
        })
        .exec();
      // console.log(foshowTop,siftTop)
      if(foshowTop < 0 && siftTop < 0){
        that.setData({
          current:3
        });
      }else if(siftTop <=0 && foshowTop>0){
        that.setData({
          current:2
        });
      }else if(foshowTop >0 && siftTop > 0){
        that.setData({
          current:1
        });
      }
    }
  }
});
